package com.zhc.dejingapi.config;


import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

//https://blog.csdn.net/continuce/article/details/131366286

@Configuration
@MapperScan(basePackages = "com.zhc.dejingapi.mapper", sqlSessionFactoryRef = "MySQLSqlSessionFactory")
public class mySqlDbConfig {


    @ConfigurationProperties(prefix = "spring.datasource.mysqldb")
    @Bean("mySqlDataSource")
    public DataSource mySqlDataSource() {
        return DataSourceBuilder.create().build();
        //return new DruidDataSource();
    }

    @Bean("mySqlTransactionManager")
    public PlatformTransactionManager mySqlTransactionManager(@Qualifier("mySqlDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean("mySqlJdbcTemplate")
    public JdbcTemplate jdbcTemplate(@Qualifier("mySqlDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean(name = "MySQLSqlSessionFactory")
    public SqlSessionFactory test1SqlSessionFactory(
            @Qualifier("mySqlDataSource") DataSource datasource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(// 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
        return bean.getObject();
    }


    @Bean("MySQLSqlSessionTemplate")
    public SqlSessionTemplate test1SqlSessionTemplate(
            @Qualifier("MySQLSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }

//    @Bean
//    public PlatformTransactionManager transactionManager1(@Qualifier("mySqlDataSource")DataSource dataSource) {
//        return new DataSourceTransactionManager(dataSource);
//    }

}
